<?php
abstract class My_Model_Abstract extends My_Object
{
    protected $_fetchMode = Zend_Db::FETCH_ASSOC;

    protected $_mainTable = '';

    protected $_resource = null;

    public function __construct()
    {
        parent::__construct();
        $this->getAdapter()->setFetchMode($this->_fetchMode);
    }

    public function save()
    {
        $this->_beforeSave();
        $data = $this->getData();
        if ($this->_validate($data)) {
            if (!$this->getId()) {
                $this->getAdapter()->insert($this->_mainTable, $data);
            } else {
                $where = $this->getAdapter()->quoteInto($this->getIdFieldName() . ' = ?', $this->getId());
                $this->getAdapter()->update($this->_mainTable, $data, $where);
            }
        }
        return $this;
    }

    public function delete()
    {
        $where = $this->getAdapter()->quoteInto($this->getIdFieldName() . ' = ?', $this->getId());
        $this->getAdapter()->delete($this->_mainTable, $where);
        return $this;
    }

    public function load($id)
    {
        $where = $this->getAdapter()->quoteInto($this->getIdFieldName() . ' = ?', $this->getId());
        $select = $this->getAdapter()->select()
        ->from($this->_mainTable)
        ->where($this->getIdFieldName() . ' = ?', $id);
        $data = $this->getAdapter()->fetchRow($select);
        if (!$data) {
            $data = array();
        }
        $this->setData($data);
        return $this;
    }

    public function getResource()
    {
        if (empty($this->_resource)) {
            $this->_resource = new My_Model_Resource();
        }
        return $this->_resource;
    }

    public function getAdapter()
    {
        return $this->getResource()->getAdapter();
    }

    protected function _beforeSave()
    {}

    protected function _validate($data)
    {
        return true;
    }
}